home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1996 #15 / Monster Media Number 15 (Monster Media)(July 1996).ISO / prog_c / cuj0896.zip / LETTERS.ZIP / REVERSIT.CPP
C/C++ Source or Header  |  1996-05-06  |  2KB  |  63 lines

  1. // reversit.cpp   use cin.get(), reverse spelling of a word or phrase.
  2. //#define STDIO
  3.  
  4. #include <string.h>
  5. #ifdef STDIO
  6. #include <stdio.h>
  7. #else
  8. #include <iostream.h>
  9. #endif
  10.  
  11. void reversit(char[]);                    // prototype
  12. void swapchar(char *cp1, char *cp2);    // prototype
  13.  
  14. const int MAX=80;                        // max string length
  15. char str[MAX];                          // global for watching in debug mode
  16.  
  17. int main(void)
  18. {
  19.     char yesno;
  20.     const char *prompt = "\nEnter a word or a phrase to reverse:\n";
  21.     do
  22.     {
  23.         str[0] = '\0';
  24. #ifdef STDIO
  25.         printf(prompt);
  26.         gets(str);
  27. #else
  28.         cout << prompt;
  29.         cin.get(str, MAX);        // read in phrase, include blanks.
  30. #endif
  31.  
  32.         reversit(str);
  33.  
  34. #ifdef STDIO
  35.         printf("\nThe reverse is:\n%s\n\nDo another? y/n", str);
  36.         yesno = getchar();
  37.         fflush(stdin);  // discard ALL characters in buffer
  38. #else
  39.         cout << "\nThe reverse is:\n" << str << "\n\nDo another? y/n";
  40.         cin >> yesno;
  41.         cin.ignore();    // discard ONE character
  42. #endif
  43.     } while (yesno == 'y');
  44.     return (0);
  45. }
  46.  
  47. void reversit(char s[])            //    function to reverse string
  48. {
  49.     int j = (strlen(s)-1);      // index of last character (not \0)
  50.     if (j<0) return;            // nothing to do if strlen == 0
  51.     for (int i = 0; i <= j/2; i++)
  52.         swapchar(&s[i], &s[j-i]);
  53. }
  54.  
  55. void swapchar(char *cp1, char *cp2) //function to swap characters
  56. {
  57.     char temp = *cp1;
  58.     *cp1 = *cp2;
  59.     *cp2 = temp;
  60. }
  61.  
  62. // end of reversit.cpp
  63.